<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;
//use think\addons\Service;
//use think\Exception;

use app\admin\model\vppz\App;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class PhysicalExamPackage extends Base
{
	protected $branch = 0;	// 0：插件市场版，1：自主授权版

    protected $model = null;

   protected $searchFields = ['id','name'];
	protected $multiFields = ['is_active'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\PhysicalExamPackage;
        $this->relModel = new \app\admin\model\vppz\PhysicalPackageItemRel;
        $this->bdmodel = new \app\admin\model\vppz\Hospital;
        $this->assign('cates',array(
            array(
                'id'=>'bijian',
                'name'=>'必检套餐'
            ),
            array(
                'id'=>'multi',
                'name'=>'组合套餐'
            ),
            array(
                'id'=>'auto',
                'name'=>'自选套餐'
            )
        )
        );
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->modelValidate = true;
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $form = $this->preExcludeFields($params);
            $result = false;
            try {
                $Note = $this->model->where(['name'=>$form['name']])->find();
                if(empty($Note) === FALSE){
					$this->error('套餐名称已存在，重试看看呢');
                }
                $hospital_name="不指定医院";
                $hospital_level="未公开";
                if(empty($form['hospital_id']) === FALSE){
                    $hospital = $this->bdmodel->where(array(
                        'id'=>$form['hospital_id']
                    ))->find();
                    if(empty($hospital) ===FALSE){
                        $hospital_name = $hospital->name;
                        $hospital_level = $hospital->rank;
                    };
                }
                $Data = array(
                    'name'=>$form['name'],
                    'app_id'=>$this->app_id,
                    'weigh'=>$form['weigh'],
                    'hospital_id'=>$form['hospital_id'],
                    'hospital_name'=>$hospital_name,
                    'hospital_level'=>$hospital_level,
                    'total_original_price'=>$form['total_original_price'],
                    'final_price'=>$form['final_price'],
                    'total_discount'=>sprintf("%.2f",$form['final_price']/$form['total_original_price']),
                    'description'=>$form['description'],
                    'people_type'=>$form['people_type'],
                    'hospital_business_hours'=>$form['hospital_business_hours'],
                    'hospital_phone'=>$form['hospital_phone'],
                    'is_active'=>$form['is_active'],
                    'cate_id'=>$form['cate_id'],
                );
                $ret = $this->model->save($Data);
                if(!$ret){
					$this->error('服务器刚刚走神了，重试看看呢');
				}
                $this->success();
            } catch (ValidateException|PDOException|Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $hospitals = $this->bdmodel->where(array(
            'is_local'=>1,
            'use_switch'=>1
        ))->whereNull('deletetime')->select();
        $this->view->assign('hospitals',$hospitals);
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);
        $result = false;
        try {
            $Note = $this->model->where(['name'=>$form['name']])->find();
            if(empty($Note) === FALSE && $Note['id'] != $ids){
                $this->error('套餐名称已存在，重试看看呢');
            }
            $hospital_name="不指定医院";
                $hospital_level="未公开";
                if(empty($form['hospital_id']) === FALSE){
                    $hospital = $this->bdmodel->where(array(
                        'id'=>$form['hospital_id']
                    ))->find();
                    if(empty($hospital) ===FALSE){
                        $hospital_name = $hospital->name;
                        $hospital_level = $hospital->rank;
                    };
                }
                if($form['cate_id'] == 'bijian'){
                    $rel = $this->relModel->where([
                        'package_id'=>$ids
                    ])->whereIn('item_type',[2,3])->find();
                    if(empty($rel) === FALSE){
                        $this->relModel->where([
                        'package_id'=>$ids
                    ])->update(array(
                            'item_type'=>1,
                            'updatetime'=>time()
                        ));
                    }
                }else if($form['cate_id'] == 'auto'){
                    $rel = $this->relModel->where([
                        'package_id'=>$ids,
                        'item_type'=>1
                    ])->find();
                    if(empty($rel) === FALSE){
                        $this->relModel->where([
                            'package_id'=>$ids,
                            'item_type'=>1
                        ])->update(array(
                            'item_type'=>3,
                            'updatetime'=>time()
                        ));
                    }
                }
            $Data = array(
                    'name'=>$form['name'],
                    'weigh'=>$form['weigh'],
                    'hospital_id'=>$form['hospital_id'],
                    'hospital_name'=>$hospital_name,
                    'hospital_level'=>$hospital_level,
                    'total_original_price'=>$form['total_original_price'],
                    'final_price'=>$form['final_price'],
                    'total_discount'=>sprintf("%.2f",$form['final_price']/$form['total_original_price']),
                    'description'=>$form['description'],
                    'people_type'=>$form['people_type'],
                    'hospital_business_hours'=>$form['hospital_business_hours'],
                    'hospital_phone'=>$form['hospital_phone'],
                    'is_active'=>$form['is_active'],
                    'cate_id'=>$form['cate_id'],
            );
            $ret = $this->model->where(['id'=>$ids])->update($Data);
            if(!$ret){
                $this->error('服务器刚刚走神了，重试看看呢');
            }
            $this->success();
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();

    }

}
